<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use think\Db;

function createCode($length=4)
{
    $string = '0123456789';
    $len = strlen($string) - 1;
    $result = '';
    for ($i = 0; $i < $length; $i++) {
        $result .= $string[rand(0, $len)];
    }
    return $result;
}
function getRandStr($len) //len字符串长度
{
    $chars = array(
        'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9');//你想填写的随机数
    $charsLen = count($chars) - 1;
    shuffle($chars);
    $output = '';
    for ($i = 0; $i < $len; $i++) {
        $output .= $chars[mt_rand(0, $charsLen)];
    }
    return $output;
}

function print_v($array,$is_die=true){
    echo "<pre>";
    print_r($array);
    if($is_die)die;
}
function get_client_ip($type = 0) {
    $type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos    =   array_search('unknown',$arr);
        if(false !== $pos) unset($arr[$pos]);
        $ip     =   trim($arr[0]);
    }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip     =   $_SERVER['HTTP_CLIENT_IP'];
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}
function package($code,$status,$data=null,$count=null)
{
    if(!empty($count)){
        $data =  [
            'code'=>$code,
            'msg'=>$status,
            'count'=>$count,
            'data'=>$data
        ];
        return json($data);
    }else{
        $data = [
            'code'=>$code,
            'msg'=>$status,
            'data'=>$data
        ];
        return  json($data);
    }
}


function db_createArray($table_name){
    $str = "[\n";
    $inf = get_db_column_comment($table_name);
    foreach ($inf as $k=>$v){
        $str.='   "'.$k.'"=>""'.",\n";
    }
    return $str.'];';

}
function get_db_column_comment($table_name = '', $field = true, $table_schema = ''){
    // 接收参数
    $database = config('database.');
    $table_schema = empty($table_schema) ? $database['database'] : $table_schema;
    $table_name = $database['prefix'] . $table_name;

    // 缓存名称
    $fieldName = $field === true ? 'allField' : $field;
    $cacheKeyName = 'db_' . $table_schema . '_' . $table_name . '_' . $fieldName;

    // 处理参数
    $param = [
        $table_name,
        $table_schema
    ];

    // 字段
    $columeName = '';
    if($field !== true){
        $param[] = $field;
        $columeName = "AND COLUMN_NAME = ?";
    }
    // 查询结果
    $result = think\Db :: query("SELECT COLUMN_NAME as field,column_comment as comment FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = ? AND table_schema = ? $columeName", $param);
    // pp(Db :: getlastsql());
    if(empty($result) && $field !== true){
        return $table_name . '表' . $field . '字段不存在';
    }
    // 处理结果
    foreach($result as $k => $v){
        $data[$v['field']] = $v['comment'];
    }
    // 字段注释格式不正确
    if(empty($data)){
        return $table_name . '表' . $field . '字段注释格式不正确';
    }
    return count($data) == 1 ? reset($data) : $data;
}
function create_listForm($table,$field){
    $info = get_db_column_comment($table);
    return view('/common/create_list',['info'=>$info,'field'=>$field,'table'=>$table]);
}
function httpGet($url) {
    $curl = curl_init();    //初始化一个cURL会话。
    curl_setopt($curl, CURLOPT_TIMEOUT, 100);  //设置cURL允许执行的最长秒数
    curl_setopt($curl, CURLOPT_URL, $url);  //URL地址
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,FALSE);  //禁用后cURL将终止从服务端进行验证
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);  //不验证证书是否存在
    curl_setopt($curl, CURLOPT_HEADER, FALSE);    //禁止后使用CURL_TIMECOND_IFUNMODSINCE，默认值为CURL_TIMECOND_IFUNMODSINCE
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);  //将curl_exec()获取的信息以文件流的形式返回，而不是直接输出
    $res = curl_exec($curl);  //执行一个cURL会话
    curl_close($curl);  //关闭一个cURL会话
    return $res;
}
function create_form($table,$field,$title,$type){
    $url =  config('public.host').'/admin.php/login/creatForm/table/'.$table.'/field/'.$field.'/title/'.$title.'/type/'.$type;
    $htm = httpGet($url);
    $path =__DIR__.strtolower('/'.request()->module().'/view/'.request()->controller().'/');
    $name =strtolower($path.request()->action().'.html');
    if (!is_dir($path)){
        mkdir($path,0777);
    }
    print_r($htm);
    return file_put_contents($name,$htm);
}
function create_list($table,$field){
    $url = config('public.host').'/admin.php/login/creatList/table/'.$table.'/field/'.$field;
    $htm = httpGet($url);
    $path =__DIR__.strtolower('/'.request()->module().'/view/'.request()->controller().'/');
    $name =strtolower($path.request()->action().'.html');
    if (!is_dir($path)){
        mkdir($path,0777);
    }
    echo $htm;
    return file_put_contents($name,$htm);
}
function createVaild($table){
    $customers_msg_all =  Db::name($table)->getFieldsType();
    return view('/common/field',['info'=>$customers_msg_all,'table'=>$table]);
}
function checkRes($result,$msg='添加',$is_none = true){
    if($result){

        $msg = $is_none?$msg."成功":$msg."";
        return package(0,$msg);
    }else{
        $msg = $is_none?$msg."失败":$msg."";
        return package(20001,$msg);
    }
}
function clientReturnJson($code,$msg='',$data=[]){
    echo  json_encode([
        'code'=>$code,
        'msg'=>$msg,
        'data'=>$data
    ],JSON_UNESCAPED_UNICODE);exit;
}
function curPageURL()
{
    $pageURL = 'http';

    if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on")
    {
        $pageURL .= "s";
    }
    $pageURL .= "://";

    if ($_SERVER["SERVER_PORT"] != "80")
    {
        $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
    }
    else
    {
        $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    }
    return $pageURL;
}
function validation_filter_id_card($id_card){
    if(strlen($id_card)==18){
        return idcard_checksum18($id_card);
    }elseif((strlen($id_card)==15)){
        $id_card=idcard_15to18($id_card);
        return idcard_checksum18($id_card);
    }else{
        return false;
    }
}

// 计算身份证校验码，根据国家标准GB 11643-1999
function idcard_verify_number($idcard_base){
    if(strlen($idcard_base)!=17){
        return false;
    }
    //加权因子
    $factor=array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);
    //校验码对应值
    $verify_number_list=array('1','0','X','9','8','7','6','5','4','3','2');
    $checksum=0;
    for($i=0;$i<strlen($idcard_base);$i++){
        $checksum += substr($idcard_base,$i,1) * $factor[$i];
    }
    $mod=$checksum % 11;
    $verify_number=$verify_number_list[$mod];
    return $verify_number;
}
// 将15位身份证升级到18位
function idcard_15to18($idcard){
    if(strlen($idcard)!=15){
        return false;
    }else{
        // 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码
        if(array_search(substr($idcard,12,3),array('996','997','998','999')) !== false){
            $idcard=substr($idcard,0,6).'18'.substr($idcard,6,9);
        }else{
            $idcard=substr($idcard,0,6).'19'.substr($idcard,6,9);
        }
    }
    $idcard=$idcard.idcard_verify_number($idcard);
    return $idcard;
}
// 18位身份证校验码有效性检查
function idcard_checksum18($idcard){
    if(strlen($idcard)!=18){
        return false;
    }
    $idcard_base=substr($idcard,0,17);
    if(idcard_verify_number($idcard_base)!=strtoupper(substr($idcard,17,1))){
        return false;
    }else{
        return true;
    }
}
function redisObj(){
    $redis = new \Redis();
    $redis->connect(config('public.user_redis.host'), config('public.user_redis.port'));
    $redis->auth(config('public.user_redis.password')); //密码验证
    $redis->select(config('public.user_redis.index'));//选择数据库2
    return $redis;
}
function xmlToArray($xml){ //xml转数组
    libxml_disable_entity_loader(true);
    $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $values;
}
function arrayToXml($arr){ //数组转xml
    $xml = "<xml>";
    foreach ($arr as $key=>$val)
    {
        if (is_numeric($val)){
            $xml.="<".$key.">".$val."</".$key.">";
        }else{
            $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
    }
    $xml.="</xml>";
    return $xml;
}
function redisHashSet($hash,$key,$value){
    $value = json_encode($value);
    return redisObj()->hSet($hash,$key,$value);
}
function redisHashDel($hash,$key){
    return redisObj()->hDel($hash,$key);
}
function redisHashGet($hash,$key){
    return json_decode(redisObj()->hGet($hash,$key),true);
}


function checkPass($p1,$p2){
    return password_verify($p1,$p2);
}

function Pass($p1){
    return password_hash($p1,PASSWORD_DEFAULT);
}
//请求数限制
preventSubmit();
function preventSubmit(){
     $config = include(dirname(__DIR__).'/config/public.php');
     if(!$config['req']) return;
     $ip=get_client_ip();
     $userAgent = md5($_SERVER['HTTP_USER_AGENT']);
     $time = intval(think\facade\Cache::get($ip));
     $time1 = intval(think\facade\Cache::get($userAgent));
     $atTime  = isset($config['req_at_time'])?$config['req_at_time']:120;
     $sTime  = isset($config['req_time'])?$config['req_time']:120;
     if($time>=$atTime){
         echo "请求频繁!";
         exit;
     }
     if($time1>=$atTime){
         echo "请求频繁!";
         exit;
     }
     think\facade\Cache::set($ip,$time+1,$sTime);
     think\facade\Cache::set($userAgent,$time1+1,$sTime);
}
function curl_post($url , $data=array()){

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    // POST数据
    curl_setopt($ch, CURLOPT_POST, 1);
    // 把post的变量加上

    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}
function http_post_json($url, $jsonStr =[], $timeout = 20){
     $ch = curl_init();

     $jsonStr = json_encode($jsonStr);
     curl_setopt($ch, CURLOPT_POST, 1);
     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_HTTPHEADER, array(
             'Content-Type: application/json; charset=utf-8',
             'Content-Length: ' . strlen($jsonStr)
         )
     );
     $response = curl_exec($ch);
//     $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
     curl_close($ch);
     return $response;
}

function curl_get($url,$result_type='json'){

    $ch = curl_init();
    //设置选项，包括URL
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//绕过ssl验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    //执行并获取HTML文档内容
    $output = curl_exec($ch);

    //释放curl句柄
    curl_close($ch);
    if($result_type=='json'){
        return json_decode($output,true);
    }
    return $output;
}
function deldir($dir) {
    //先删除目录下的文件：
    $dh=opendir($dir);
    while ($file=readdir($dh)) {
        if($file!="." && $file!="..") {
            $fullpath=$dir."/".$file;
            if(!is_dir($fullpath)) {
                unlink($fullpath);
            } else {
                deldir($fullpath);
            }
        }
    }

    closedir($dh);
    //删除当前文件夹：
    if(rmdir($dir)) {
        return true;
    } else {
        return false;
    }
}